/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "taskbarappmanager.h"
#include <QStandardPaths>
#include <QFile>
#include <QSettings>
#include "ukuisettings.h"

static const QStringList defaultTaskbarApps = {
    "/usr/share/applications/peony.desktop",
    "/usr/share/applications/kylin-software-center.desktop",
    "/usr/share/applications/wps-office-wps.desktop"
};

TaskbarAppManager::TaskbarAppManager(QObject *parent)
    : QObject{parent}
{
    loadSettingsFile();

    m_fileWatcher = new QFileSystemWatcher(this);
    if (m_settingsFile.isEmpty()) {
        qWarning() << "m_settingsFile is empty !!!" << __func__;
        return;
    }
    m_fileWatcher->addPath(m_settingsFile);
    connect(m_fileWatcher, SIGNAL(fileChanged(const QString &)), this, SLOT(taskBarDataChanged()));
}

QStringList TaskbarAppManager::appDesktopfiles() const
{
    return m_appsDesktopFiles;
}

void TaskbarAppManager::checkAppDesktopfiles(const QStringList &preDesktopfiles)
{
    m_appsDesktopFiles = preDesktopfiles;
    taskBarDataChanged();
}

void TaskbarAppManager::updatePanelConf(const QList<QString> &taskbarData)
{
    QList<QMap<QString, QVariant>> hashList;
    for (int i = 0; i < taskbarData.size(); ++i) {
        QString desktopName = taskbarData.at(i);
        QHash<QString, QString> m_settingsMap;
        m_settingsMap["desktop"] = desktopName;

        QMap<QString, QVariant> map;
        QHashIterator<QString, QString> it(m_settingsMap);
        while (it.hasNext()) {
            it.next();
            map[it.key()] = it.value();
        }
        hashList << map;
    }
    Settings settings(m_settingsFile, QSettings::IniFormat,"taskbar", this);
    settings.setArray("apps", hashList);
    m_appsDesktopFiles = taskbarData;
}

void TaskbarAppManager::loadSettingsFile()
{
    auto locations = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation);
    if (!locations.isEmpty()) {
        m_settingsFile = locations.constFirst() + "/ukui/panel.conf";
        if (!QFile::exists(m_settingsFile)) {
            m_settingsFile.clear();
        }
    } else {
        if (QFile::exists("/usr/share/ukui/panel.conf")) {
            m_settingsFile = "/usr/share/ukui/panel.conf";
        }
    }
    if (!m_settingsFile.isEmpty()) {
        Settings settings(m_settingsFile, QSettings::IniFormat,"taskbar", this);
        auto taskbarApps = settings.readArray("apps");
        for (auto &app : qAsConst(taskbarApps)) {
            m_appsDesktopFiles.append(app.value("desktop").toString());
        }
    } else {
        qWarning() << "settingsFile is empty !!!" << __func__;
        m_appsDesktopFiles = defaultTaskbarApps;
    }
}

QStringList TaskbarAppManager::readTaskbarPanelConf()
{
    QStringList taskBarAppDesktop;
    if (m_settingsFile.isEmpty()) {
        qWarning() << "m_settingsFile is empty !!!" << __func__;
        return taskBarAppDesktop;
    }
    Settings settings(m_settingsFile, QSettings::IniFormat,"taskbar", this);
    QList<QMap<QString, QVariant> > taskBarApp = settings.readArray("apps");
    for (int var = 0; var < taskBarApp.size(); ++var) {
        taskBarAppDesktop.push_back(taskBarApp[var]["desktop"].toString());
    }
    return taskBarAppDesktop;
}

void TaskbarAppManager::taskBarDataChanged()
{
    qDebug() << "任务栏配置文件发生改变！" << __FUNCTION__;
    if (m_settingsFile.isEmpty()) {
        qWarning() << "m_settingsFile is empty !!!" << __func__;
        return;
    }
    m_fileWatcher->addPath(m_settingsFile);

    QStringList taskBarAppDesktop = readTaskbarPanelConf();
    if (taskBarAppDesktop == m_appsDesktopFiles) {
        return;
    }
    //与pc任务栏同步
    //先调整应用顺序，添加缺少的应用
    //最后将未显示在pc任务栏的应用从任务栏移出
    QStringList tmpTaskbarAppDesktopData = m_appsDesktopFiles;
    for (int i = 0; i < taskBarAppDesktop.count(); ++i) {
        QString tmpDesktopName = taskBarAppDesktop.at(i);
        int desktopIndexOf = tmpTaskbarAppDesktopData.indexOf(tmpDesktopName);
        if (desktopIndexOf == i) {
            continue;
        }
        if (desktopIndexOf > 0 && i < tmpTaskbarAppDesktopData.count()) {
            tmpTaskbarAppDesktopData.move(desktopIndexOf, i);
            Q_EMIT taskbarAppChanged(tmpTaskbarAppDesktopData, TaskbarAction::Move);
        }
        if (desktopIndexOf < 0) {
            tmpTaskbarAppDesktopData.insert(i, tmpDesktopName);
            Q_EMIT taskbarAppChanged(tmpTaskbarAppDesktopData, TaskbarAction::Add);
        }
    }
    if (taskBarAppDesktop.count() < tmpTaskbarAppDesktopData.count()) {
        for (int j = taskBarAppDesktop.count();
                 j < tmpTaskbarAppDesktopData.count();
                 ++j) {
            tmpTaskbarAppDesktopData.removeAt(j);
            Q_EMIT taskbarAppChanged(taskBarAppDesktop, TaskbarAction::Delete);
        }
    }
    m_appsDesktopFiles = taskBarAppDesktop;
}

